package com.company.huisuo.network

import com.company.huisuo.BuildConfig
import com.company.huisuo.network.interceptor.TokenInterceptor
import com.company.huisuo.network.interceptor.TokenRefreshInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Retrofit客户端管理类
 */
object RetrofitClient {
    
    private const val BASE_URL = "http://106.54.244.250:8081/" // API服务器地址
    
    private val okHttpClient: OkHttpClient by lazy {
        val builder = OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
        
        // 添加token拦截器
        builder.addInterceptor(TokenInterceptor())
        
        // 添加token刷新拦截器
        builder.addInterceptor(TokenRefreshInterceptor())
        
        // 添加日志拦截器（仅在调试模式下）
        if (BuildConfig.DEBUG) {
            val loggingInterceptor = HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            }
            builder.addInterceptor(loggingInterceptor)
        }
        
        builder.build()
    }
    
    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
    
    /**
     * 创建API服务实例
     */
    fun <T> createService(serviceClass: Class<T>): T {
        return retrofit.create(serviceClass)
    }
    
    /**
     * 创建API服务实例（使用reified关键字）
     */
    inline fun <reified T> createService(): T {
        return createService(T::class.java)
    }
}